from datetime import date
from flask import Flask,request,jsonify
from flask_cors import CORS
#对象关系映射
from flask_sqlalchemy import SQLAlchemy
from Config import Config
import json
from math import ceil
import os




app = Flask(__name__)
app.config.from_object(Config)
CORS(app)
db = SQLAlchemy(app)

class Ncate(db.Model):
    __tablename__='ncate'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(40),default='')
    types = db.Column(db.Integer,default=1)
    parent = db.Column(db.Integer,default=0)

class Course(db.Model):
    __tablename__='ncourse'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),unique=True)#名称唯一
    description = db.Column(db.Text,default='')#描述
    tname = db.Column(db.String(50),default='')#讲师
    pic = db.Column(db.String(255),default='')#图片
    vedios = db.Column(db.String(255),default='')#视频['','']
    status = db.Column(db.Integer,default=1)#审核状态
    reason=db.Column(db.String(255),default='')#失败原因
    cid =  db.Column(db.Integer,db.ForeignKey('ncate.id'))#所属分类
# db.create_all()
@app.route('/add_ncate',methods=['POST','GET','DELETE','PUT'])
def main():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        ncate = Ncate(name=data['name'])
        db.session.add(ncate)
        db.session.commit()
        return jsonify({'code':200})
    elif request.method == 'GET':
        cpage = request.args.get('cpage')
        if cpage:
            page_size = 2
            start = (int(cpage)-1)*page_size
            ncate = Ncate.query.offset(start).limit(page_size)

            
            list1 = []
            for i in ncate:
                dict1 = {'id':i.id,'name':i.name,'types':i.types}
                list1.append(dict1)
            tpage = Ncate.query.count()
            total = ceil(tpage/page_size)

            return jsonify({'code':200,'list':list1,'total':total})
        else:
            ncate = Ncate.query.all()
            list2 = []
            for i in ncate:
                dict1 = {'id':i.id,'name':i.name,'types':i.types}
                list2.append(dict1)
            return jsonify({'code':200,'list':list2})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        Ncate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({'code':200})
    else:
        id = request.args.get('id')
        name = request.args.get('name')
        Ncate.query.filter_by(id=id).update({'name':name})
        db.session.commit()
        return jsonify({'code':200})

@app.route('/upload',methods=['POST'])
def method_name():
    file = request.files['file']
    file.save(os.path.join('./static/upload/',file.filename))
    try: 
        id = request.form.get('id')
        Course.query.filter_by(id=id).update({'pic':file.filename})
        db.session.commit()
    except:
        pass
    
    return jsonify({"code":200,'pic':file.filename})
    
@app.route('/add_ncourse',methods=['POST','GET'])
def add_ncourse():
    if request.method=='POST':
        data = request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        course = Course(name=data['name'],description=data['description'],tname=data['tname'],pic=data['pic'],vedios=json.dumps(data['vedios'],ensure_ascii=False),cid=data['cid'],)
        db.session.add(course)
        db.session.commit()
        return jsonify({'code':200})
    elif request.method=='GET':
        cpage = int(request.args.get('cpage'))
        size = int(request.args.get('size'))
        start = (cpage-1)*size
        course = Course.query.offset(start).limit(size)
        list=[]
        if course:
            for i in course:
                dict={'id':i.id,'name':i.name,'pic':i.pic,'tname':i.tname}
                list.append(dict)
        tpage = Course.query.count()
        total = ceil(tpage/size)
        return jsonify({'code':200,'list':list,'total':total})

@app.route('/put_course',methods=['PUT','GET'])
def put_course():
    if request.method=='GET':
        id = request.args.get('id')
        course = Course.query.filter_by(id=id).first()
        list = {'id':course.id,'name':course.name,'description':course.description,'tname':course.tname,'pic':course.pic,'vedios':course.vedios,'cid':course.cid}
        return jsonify({'code':200,'list':list})
    elif request.method=='PUT':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        course = Course.query.filter_by(id=data['id']).update({'name':data['name'],'description':data['description'],'tname':data['tname'],'cid':data['cid'],'pic':data['pic'],'vedios':data['vedios']})
        db.session.commit()
        return jsonify({'code':200})

@app.route('/delpic',methods=['DELETE'])
def delpic():
    name = request.args.get('name')
    if not name:
        return jsonify({'code':10010,'mes':'无删除的文件'})
    else:
        os.remove('./static/upload/'+name)
        #更新表中数据
        id = request.args.get('id')
        Course.query.filter_by(id=id).update({'pic':''})
        db.session.commit()
        return jsonify({'code':200})

            
        

        

if __name__ == '__main__':
    app.run(debug=True)